//
//  RestaurantsViewController.m
//  ClassifyShop
//
//  Created by yuyao on 15/3/21.
//  Copyright (c) 2015年 yuyao. All rights reserved.
//

#import "RestaurantsViewController.h"
#import "GUIDefine.h"

#import "RestaurantTableViewCell.h"
#import "RestaurantPopView.h"
#import "RestaurantDetailViewController.h"

@interface RestaurantsViewController ()<PullingRefreshTableViewDelegate,UITableViewDataSource,UITableViewDelegate,NetWorkModalDelegate>{
    NSMutableArray *datas;
    PullingRefreshTableView *table;
    
    int totalPages;
    int currentPage;
    NetWorkModal *netModal;
    RestaurantPopView *popView;
    RestaurantDetailViewController *restaurantDetailViewController;
    NSString *requestDescribeString;
}


@end

@implementation RestaurantsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self.view setBackgroundColor:[UIColor whiteColor]];
        
        ADDLEFTBTN(self, @"back.png", @"", @selector(back));
        ADDRIGHTBTN(self, @"3 菜单按钮.png", @"", @selector(shouPopView),25);
        
        table = [[PullingRefreshTableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64) style:UITableViewStylePlain];
        [table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
        [table setDelegate:self];
        [table setDataSource:self];
        [table setPullingDelegate:self];
        [self.view addSubview:table];
        netModal = [NetWorkModal sharedInstance];
        
        datas = [NSMutableArray array];
        currentPage = 1;
        
    }
    return self;
}
- (void)getAllRestaurants{
    [netModal setDelegate:self];
  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    requestDescribeString = @"刷新成功";
    [netModal getRestaurantListWithKeyWord:@"" andPageNumber:1];
}

#pragma mark getRestaurantListDelegateMethod
- (void)getRestaurantListDelegateMethod:(NSArray *)array andPagesize:(int)pagesize{
    [MBProgressHUD hideHUDForView:self.view animated:YES];

    if (array==nil) {
        [[[[iToast makeText:@"网络可能出问题了亲～～～"]
           setGravity:iToastGravityBottom] setDuration:iToastDurationNormal] show];
        [table tableViewDidFinishedLoading];
        return;
    }
    
    NSLog(@"pagesize=%d",pagesize);
    totalPages = pagesize;
    
    if ([requestDescribeString isEqualToString:@"刷新成功"]) {
        [datas setArray:array];
    }else{
        if (array.count>0) {
            [datas addObjectsFromArray:array];
        }else{
            requestDescribeString = @"请求更多失败";
            currentPage = currentPage-1;
        }
    }
    
    [[[[iToast makeText:requestDescribeString]
       setGravity:iToastGravityBottom] setDuration:iToastDurationNormal] show];
    
    [table reloadData];
    [table tableViewDidFinishedLoading];
    
}
- (void)back{
    UIImageView *titleBackImage = (UIImageView *)[self.navigationController.navigationBar viewWithTag:123];
    [UIView animateWithDuration:0.2 animations:^{
        
        [titleBackImage setAlpha:1];
        
    }];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [netModal setDelegate:self];
}
- (void)shouPopView{
    if (popView==nil) {
        popView = [[RestaurantPopView alloc] initWithFrame:CGRectMake(0, 0, kAppScreenWidth, kAppScreenHeight)];
        [popView addTarget:self action:@selector(closePopView) forControlEvents:UIControlEventTouchUpInside];
    }
    if (popView.superview==nil) {
        [self.navigationController.view addSubview:popView];
    }
}
- (void)closePopView{
    [popView removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return datas.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"mycell";
    
    RestaurantTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (cell==nil) {
        
        cell = [[RestaurantTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        
    }
    RestaurantCore *rcore = [datas objectAtIndex:indexPath.row];
    
    
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    [cell.typeLabel setText:rcore.name];
    
    [cell.titleLabel setText:rcore.name];
    
    UIFont *fnt = [UIFont fontWithName:@"Arial" size:12.0f];
    
    CGSize size = [cell.titleLabel.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:fnt,NSFontAttributeName, nil]];
    [cell.titleLabel setFrame:CGRectMake(10, 0, size.width, 25)];
    
    [cell.starRateView setScorePercent:0.3];
    [cell.starRateView setFrame:CGRectMake(cell.titleLabel.frame.size.width+15, 5, 60, 15)];
    
    // [cell.avCostLabel setText:@"平均消费：50"];
    [cell.shiyongLabel setText:rcore.recommend];
    
    NSURL *portraitUrl = [NSURL URLWithString:rcore.thumb];
    
    [cell.bigImageView setImageWithURL:portraitUrl];
    
    [cell.shoucangImage setImage:[UIImage imageNamed:@"7 收藏.png"]];
    [cell.shoucangLabel setText:@"收藏"];
    
    [cell setFrame:CGRectMake(0, 0,kAppScreenWidth, (kAppScreenWidth-100)/2)];
    
    return cell;
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell = [self tableView:tableView cellForRowAtIndexPath:indexPath];
    
    return cell.frame.size.height;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (restaurantDetailViewController==nil) {
        restaurantDetailViewController = [[RestaurantDetailViewController alloc] initWithNibName:nil bundle:nil];
    }
    RestaurantCore *rc = [datas objectAtIndex:indexPath.row];
    [restaurantDetailViewController setTitle:rc.name];
    [restaurantDetailViewController getRestaurantWithRestaurantId:rc.restId];
    [self.navigationController pushViewController:restaurantDetailViewController animated:YES];
}

#pragma mark - Scroll

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    [table tableViewDidScroll:scrollView];
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [table tableViewDidEndDragging:scrollView];
    
}


#pragma mark - PullingRefreshTableViewDelegate
// 下拉刷新时，触发的回调函数
- (void)pullingTableViewDidStartRefreshing:(PullingRefreshTableView *)tableView
{
    [self refreshDataSource:tableView];
}

// 上拉加载数据时触发的函数
- (void)pullingTableViewDidStartLoading:(PullingRefreshTableView *)tableView
{
    [self loadDataSource:tableView];
}
/*
 * 刷新数据操作
 */

- (void) refreshDataSource:(PullingRefreshTableView *) tableView
{
    
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [self refreshData];
}

/*
 * 加载数据操作
 */
- (void) loadDataSource:(PullingRefreshTableView *) tableView
{
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [self performSelector:@selector(requestMoreData) withObject:nil afterDelay:1.0];
    
}

- (void)refreshData{
    [MBProgressHUD  hideAllHUDsForView:self.view animated:YES];
    requestDescribeString = @"刷新成功";
    currentPage = 1;
    [netModal getRestaurantListWithKeyWord:@"" andPageNumber:currentPage];
    
}
- (void)requestMoreData{
    [MBProgressHUD  hideAllHUDsForView:self.view animated:YES];
    requestDescribeString=@"请求更多成功";
    
    if (currentPage==totalPages) {
        [[[[iToast makeText:@"没有更多内容了"]
           setGravity:iToastGravityBottom] setDuration:iToastDurationNormal] show];
        [table tableViewDidFinishedLoading];
        
        return;
    }
    
    currentPage = currentPage+1;
    
    [netModal getRestaurantListWithKeyWord:@"" andPageNumber:currentPage];
    
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
